﻿using System;
using System.Collections.Generic;

namespace Chess.Common.Game
{
    public class Board
    {
        private Piece[][] _pieces;
        private List<Piece> _casualties;

        public Board()
        {
            _pieces = new Piece[8][];

            for (int i = 0; i < 8; i++)
            {
                _pieces[i] = new Piece[8];
            }

            _casualties = new List<Piece>();

            InitializeBoard();
        }

        public Piece GetPiece(Coordinate coordinate)
        {
            Tuple<int, int> indices = coordinate.ToIndices();
            return _pieces[indices.Item1][indices.Item2];
        }

        private void SetPiece(Coordinate coordinate, Piece piece)
        {
            Tuple<int, int> indices = coordinate.ToIndices();
            _pieces[indices.Item1][indices.Item2] = piece;
        }

        private void InitializePiece(PieceType type, char file, int rank, Color color)
        {
            Coordinate coordinate = new Coordinate(file,(char)(color == Color.Black
                                                                      ? '1' + rank
                                                                      : '8' - rank));
            Piece piece = new Piece(type, color);
            SetPiece(coordinate, piece);
        }

        private void InitializePieces(PieceType type, char file, int rank)
        {
            InitializePiece(type, file, rank, Color.Black);
            InitializePiece(type, file, rank, Color.White);
        }

        private void InitializeBoard()
        {
            foreach (PieceType piece in Enum.GetValues(typeof(PieceType)))
            {
                List<char> files = piece.GetFiles();
                int rank = piece.GetRank(); // offset from back
                files.ForEach(file => InitializePieces(piece, file, rank));
            }
        }
    }
}
